﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Duality;
using Duality.Components;
using Duality.Resources;

using OpenTK;
using OpenTK.Input;

using MagicPrototype.MagicSystem;

namespace MagicPrototype.TestStuff
{
	[Serializable]
    public class Player : Component, ICmpUpdatable
    {
		private	Character	controlObject	= null;
		
		[NonSerialized] private	Spell		activeSpell		= null;
		[NonSerialized] private	List<Spell>	spells			= new List<Spell>();
		
		public Character ControlObject
		{
			get { return this.controlObject; }
			set { this.controlObject = value; }
		}
		
		void ICmpUpdatable.OnUpdate()
		{
			SpellScriptEditor editor = Scene.Current.FindComponent<SpellScriptEditor>(false);

			for (int i = this.spells.Count - 1; i >= 0; i--)
			{
				Spell spell = this.spells[i];
				spell.Update();
				if (!spell.IsActive)
				{
					if (spell == this.activeSpell) this.activeSpell = null;
					this.spells.RemoveAt(i);
				}
			}

			if (this.controlObject != null && (editor == null || !editor.Active))
			{
				// Cast
				if (editor != null)
				{
					if (DualityApp.Mouse.ButtonHit(MouseButton.Left))
					{
						if (this.activeSpell == null)
						{
							this.activeSpell = Spell.Cast(this.controlObject, editor.Script);
							this.spells.Add(this.activeSpell);
						}
					}

					if (!DualityApp.Mouse[MouseButton.Left])
					{
						if (this.activeSpell != null)
						{
							this.activeSpell.Release();
							this.activeSpell = null;
						}
					}
				}

				// Move
				float targetSpeed = 5.0f;
				Vector2 targetVel = Vector2.Zero;
				targetVel = Vector2.Zero;
				if (DualityApp.Keyboard[Key.W])
					targetVel -= Vector2.UnitY;
				if (DualityApp.Keyboard[Key.A])
					targetVel -= Vector2.UnitX;
				if (DualityApp.Keyboard[Key.S])
					targetVel += Vector2.UnitY;
				if (DualityApp.Keyboard[Key.D])
					targetVel += Vector2.UnitX;
				targetVel /= MathF.Max(targetVel.Length, 1.0f);

				this.controlObject.TargetVel = (targetVel != Vector2.Zero) ? targetVel * targetSpeed : targetVel;
				this.controlObject.TargetDir = (new Vector2(DualityApp.Mouse.X, DualityApp.Mouse.Y) - (DualityApp.TargetResolution * 0.5f)).Angle;
			}
			else
			{
				this.controlObject.TargetVel = Vector2.Zero;
			}

			if (DualityApp.Keyboard.KeyHit(Key.P) && editor != null)
			{
				editor.Active = !editor.Active;
			}
		}
	}
}
